import logging
from django.conf import settings

logger = logging.getLogger(__name__)

class SpeechRecognitionService:
    def __init__(self, service_type='mock'):
        self.service_type = service_type
        
    def recognize_audio(self, audio_file):
        if self.service_type == 'tencent':
            return self._tencent_recognition(audio_file)
        else:
            return self._mock_recognition(audio_file)

    def _mock_recognition(self, audio_file):
        return {
            'success': True,
            'text': f"这是一段模拟的语音识别结果，音频文件大小: {len(audio_file.read())} 字节",
            'confidence': 0.95
        }

    def _tencent_recognition(self, audio_file):
        try:
            from django.conf import settings
            secret_id = getattr(settings, 'TENCENT_SECRET_ID', '')
            secret_key = getattr(settings, 'TENCENT_SECRET_KEY', '')

            if not secret_id or not secret_key:
                return {
                    'success': False,
                    'error': '腾讯云配置缺失，请检查TENCENT_SECRET_ID和TENCENT_SECRET_KEY设置'
                }

            from tencentcloud.common import credential
            from tencentcloud.common.profile.client_profile import ClientProfile
            from tencentcloud.common.profile.http_profile import HttpProfile
            from tencentcloud.asr.v20190614 import asr_client, models
            import json

            cred = credential.Credential(secret_id, secret_key)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "asr.tencentcloudapi.com"
            httpProfile.reqTimeout = 30

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = asr_client.AsrClient(cred, "ap-beijing", clientProfile)

            audio_data = audio_file.read()

            req = models.SentenceRecognitionRequest()
            params = {
                "ProjectId": 0,
                "SubServiceType": 2,
                "EngSerViceType": "16k_zh",
                "SourceType": 1,
                "VoiceFormat": "webm",
                "UsrAudioKey": "meeting-audio",
                "Data": audio_data,
                "DataLen": len(audio_data)
            }
            req.from_json_string(json.dumps(params))

            resp = client.SentenceRecognition(req)

            return {
                'success': True,
                'text': resp.Result,
                'confidence': resp.Confidence / 100.0
            }
        except ImportError:
            return {
                'success': False,
                'error': '腾讯云SDK未安装，请运行: pip install tencentcloud-sdk-python'
            }
        except Exception as e:
            logger.error(f"腾讯云语音识别失败: {str(e)}")
            error_msg = str(e)
            if 'NetworkError' in error_msg or 'timeout' in error_msg.lower() or '连接' in error_msg:
                return {
                    'success': False,
                    'error': '网络连接问题，请检查网络后重试'
                }
            elif 'AuthFailure' in error_msg:
                return {
                    'success': False,
                    'error': '腾讯云认证失败，请检查密钥配置'
                }
            elif 'LimitExceeded' in error_msg:
                return {
                    'success': False,
                    'error': '腾讯云API调用频率超限，请稍后重试'
                }
            elif 'InvalidParameter' in error_msg:
                return {
                    'success': False,
                    'error': '音频参数无效，请检查音频格式'
                }
            elif 'ResourceNotFound' in error_msg:
                return {
                    'success': False,
                    'error': '腾讯云资源未找到，请检查配置'
                }
            elif 'FailedOperation' in error_msg:
                return {
                    'success': False,
                    'error': '腾讯云服务操作失败，请稍后重试'
                }
            else:
                return {
                    'success': False,
                    'error': f'腾讯云语音识别失败: {str(e)}'
                }

def get_speech_recognition_service():
    service_type = getattr(settings, 'SPEECH_RECOGNITION_SERVICE', 'mock')
    return SpeechRecognitionService(service_type)